//
// Created by WenDaojiang on 15/11/22.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import "HybridSocialInitialize.h"
#import "HybridBridge.h"

@implementation HybridSocialInitialize

+ (HybridSocialInitialize *)instance {
    static HybridSocialInitialize *_instance = nil;

    @synchronized (self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }

    return _instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initConfig];
    }

    return self;
}

- (void)initConfig{
    NSLog(@"HybridSocialInitialize initConfig ...............");
    _platformMaps = @{
            /**
             *  未知
             */
            @"Unknown" : @(SSDKPlatformTypeUnknown),
            /**
             *  新浪微博
             */
            @"SinaWeibo" : @(SSDKPlatformTypeSinaWeibo),
            /**
            *  腾讯微博
            */
            @"TencentWeibo" : @(SSDKPlatformTypeTencentWeibo),
            /**
            *  豆瓣
            */
            @"DouBan" : @(SSDKPlatformTypeDouBan),
            /**
            *  QQ空间
            */
            @"SubTypeQZone" : @(SSDKPlatformSubTypeQZone),
            /**
            *  人人网
            */
            @"Renren" : @(SSDKPlatformTypeRenren),
            /**
            *  开心网
            */
            @"Kaixin" : @(SSDKPlatformTypeKaixin),
            /**
            *  Facebook
            */
            @"Facebook" : @(SSDKPlatformTypeFacebook),
            /**
            *  Twitter
            */
            @"Twitter" : @(SSDKPlatformTypeTwitter),
            /**
            *  印象笔记
            */
            @"YinXiang" : @(SSDKPlatformTypeYinXiang),
            /**
            *  Google+
            */
            @"GooglePlus" : @(SSDKPlatformTypeGooglePlus),
            /**
            *  Instagram
            */
            @"Instagram" : @(SSDKPlatformTypeInstagram),
            /**
            *  LinkedIn
            */
            @"LinkedIn" : @(SSDKPlatformTypeLinkedIn),
            /**
            *  Tumblr
            */
            @"Tumblr" : @(SSDKPlatformTypeTumblr),
            /**
            *  邮件
            */
            @"Mail" : @(SSDKPlatformTypeMail),
            /**
            *  短信
            */
            @"SMS" : @(SSDKPlatformTypeSMS),
            /**
            *  拷贝
            */
            @"Copy" : @(SSDKPlatformTypeCopy),
            /**
            *  微信好友
            */
            @"WechatSession" : @(SSDKPlatformSubTypeWechatSession),
            /**
            *  微信朋友圈
            */
            @"WechatTimeline" : @(SSDKPlatformSubTypeWechatTimeline),
            /**
            *  QQ好友
            */
            @"QQFriend" : @(SSDKPlatformSubTypeQQFriend),
            /**
            *  Pocket
            */
            @"Pocket" : @(SSDKPlatformTypePocket),
            /**
            *  有道云笔记
            */
            @"YouDaoNote" : @(SSDKPlatformTypeYouDaoNote),
            /**
            *  Pinterest
            */
            @"Pinterest" : @(SSDKPlatformTypePinterest),
            /**
            *  Flickr
            */
            @"Flickr" : @(SSDKPlatformTypeFlickr),
            /**
            *  微信收藏
            */
            @"WechatFav" : @(SSDKPlatformSubTypeWechatFav),
            /**
            *  Line
            */
            @"Line" : @(SSDKPlatformTypeLine),
            /**
            *  WhatsApp
            */
            @"WhatsApp" : @(SSDKPlatformTypeWhatsApp),
            /**
            *  KaKao Talk
            */
            @"KakaoTalk" : @(SSDKPlatformSubTypeKakaoTalk),
            /**
            *  KaKao Story
            */
            @"KakaoStory" : @(SSDKPlatformSubTypeKakaoStory),
            /**
            *  支付宝好友
            */
            @"AliPaySocial" : @(SSDKPlatformTypeAliPaySocial),
            /**
            *  KaKao
            */
            @"Kakao" : @(SSDKPlatformTypeKakao),
            /**
            *  印象笔记国际版
            */
            @"Evernote" : @(SSDKPlatformTypeEvernote),
            /**
            *  微信平台,
            */
            @"Wechat" : @(SSDKPlatformTypeWechat),
            /**
            *  QQ平台
            */
            @"QQ" : @(SSDKPlatformTypeQQ),
            /**
            *  任意平台
            */
            @"Any" : @(SSDKPlatformTypeAny)
    };

    NSDictionary *socialInfo = [[HybridBridge defaultHybridBridge] appInfo][@"Social"];
    if(socialInfo == nil){
        NSLog(@"Social config not found.");
        return;
    }
    NSDictionary *appKeyList = socialInfo[@"AppKeyList"];
    NSMutableDictionary *appKeys = [NSMutableDictionary dictionaryWithCapacity:appKeyList.count];
    for(id key in appKeyList){
        if(_platformMaps[key] != nil){
            appKeys[_platformMaps[key]] = appKeyList[key];
        }
    }

    NSArray *activePlatforms = socialInfo[@"activePlatforms"];
    NSMutableArray *activePlatformList = [NSMutableArray arrayWithCapacity: activePlatforms.count];
    for (int i = 0; i < activePlatforms.count; ++i) {
        [activePlatformList addObject:_platformMaps[activePlatforms[i]]];
    }
    //NSLog(@"activePlatformList %@", activePlatformList);

    /**
    *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
    *  在将生成的AppKey传入到此方法中。
    *  方法中的第二个第三个参数为需要连接社交平台SDK时触发，
    *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
    *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
    */
    [ShareSDK registerApp: socialInfo[@"ShareSdkAppKey"]

          activePlatforms: activePlatformList
                 onImport:^(SSDKPlatformType platformType) {
                     switch (platformType) {
                         case SSDKPlatformTypeWechat:
                             [ShareSDKConnector connectWeChat:[WXApi class]];
                             break;
                         case SSDKPlatformTypeQQ:
                             [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                             break;
                         case SSDKPlatformTypeSinaWeibo:
//                             [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                             break;

                         case SSDKPlatformTypeRenren:
                             [ShareSDKConnector connectRenren:[RennClient class]];
                             break;
                         default:
                             break;
                     }
                 }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {

              NSDictionary *config = [NSDictionary dictionaryWithDictionary:appKeys[@(platformType)]];


              switch (platformType) {
                  case SSDKPlatformTypeSinaWeibo:
                      //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                      [appInfo SSDKSetupSinaWeiboByAppKey: config[@"AppKey"]
                                                appSecret: config[@"AppSecret"]
                                              redirectUri: config[@"RedirectUri"]
                                                 authType: SSDKAuthTypeBoth];
                      break;
                  case SSDKPlatformTypeWechat:
                      [appInfo SSDKSetupWeChatByAppId: config[@"AppKey"]
                                            appSecret: config[@"AppSecret"]];
                      break;
                  case SSDKPlatformTypeQQ:
                      [appInfo SSDKSetupQQByAppId: config[@"AppKey"]
                                           appKey: config[@"AppSecret"]
                                         authType:SSDKAuthTypeBoth];
                      break;
                  case SSDKPlatformTypeRenren:
                      [appInfo SSDKSetupRenRenByAppId: config[@"AppId"]
                                               appKey: config[@"AppKey"]
                                            secretKey: config[@"AppSecret"]
                                             authType:SSDKAuthTypeBoth];
                      break;
                  default:
                      break;
              }
          }];
}

+ (id)Nil2NSNull:(id)var{
    if (var == nil)return [NSNull null];
    return var;
}

+ (NSDictionary *)User2Dictionary:(SSDKUser *)user {
    if(user == nil)return nil;
    return @{
            @"uid" : [self Nil2NSNull:user.uid],
            @"nickname" : [self Nil2NSNull:user.nickname],
            @"gender" : @(user.gender),
            @"birthday" : @(user.birthday.timeIntervalSince1970),
            @"aboutMe" : [self Nil2NSNull:user.aboutMe],
            @"icon" : [self Nil2NSNull:user.icon],
            @"url" : [self Nil2NSNull:user.url],
            @"regAt" : @(user.regAt), //注册时间
            @"level" : @(user.level),
            @"educations" : [self Nil2NSNull:user.educations], //教育信息
            @"works" : [self Nil2NSNull:user.works], //职业信息
            @"platformType" : @(user.platformType),
            @"followerCount" : @(user.followerCount),
            @"shareCount" : @(user.shareCount),
            @"friendCount" : @(user.friendCount),
            @"verifyType" : @(user.verifyType),
            @"verifyReason" : [self Nil2NSNull:user.verifyReason],

            @"token" : [self Nil2NSNull:user.credential.token],
            @"secret" : [self Nil2NSNull:user.credential.secret],
            @"credential" : @{
                    @"token" : [self Nil2NSNull:user.credential.token],
                    @"type" : @(user.credential.type),
                    @"available" : @(user.credential.available),
                    @"expired" : @(user.credential.expired.timeIntervalSince1970),
                    @"secret" : [self Nil2NSNull:user.credential.secret],
                    @"uid" : [self Nil2NSNull:user.credential.uid],
                    @"rawData" : [self Nil2NSNull:user.credential.rawData],
            },
            //原始数据
            @"rawData" : [self Nil2NSNull:user.rawData],
    };
}

@end